package com.ninong.ker.admin.sevice.impl;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.ninong.ker.admin.rest.vo.MenuVO;
import com.ninong.ker.common.auth.SecurityAdmin;
import com.ninong.ker.common.tools.PropertyUtil;
import com.ninong.ker.common.tools.SystemConstant;
import com.ninong.ker.common.user.OnlineUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ninong.ker.admin.domain.Menu;
import com.ninong.ker.admin.domain.MenuName;
import com.ninong.ker.admin.domain.RoleMenu;
import com.ninong.ker.admin.mapper.MenuMapper;
import com.ninong.ker.admin.mapper.MenuNameMapper;
import com.ninong.ker.admin.mapper.RoleMenuMapper;
import com.ninong.ker.admin.sevice.MenuService;
import com.ninong.ker.common.exception.CmdException;
import com.ninong.ker.common.tools.Constants;

/**
 * @author cmd
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    private static final String PARENT = "0";
    private static final String MENU = "menu";
    @Autowired
    private SecurityAdmin securityAdmin;

    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private MenuNameMapper menuNameMapper;

    @Override
    public List<MenuVO> listTree(Menu dto) {
        OnlineUser onlineUser = securityAdmin.currentUser();
        String tenantId = onlineUser.getTenantId();
        dto.setPid(PARENT);
        if (StringUtils.equalsIgnoreCase(tenantId, SystemConstant.ROOT_PARENT_ID)) {
            return baseMapper.selectMenuTree(dto);
        } else{
            dto.setTenantId(tenantId);
            return baseMapper.selectMenuTreeByTenant(dto);
        }
    }

    @Override
    public List<Menu> listMenusTree(Menu dto) {
        OnlineUser onlineUser = securityAdmin.currentUser();
        String tenantId = onlineUser.getTenantId();
        LambdaQueryWrapper<Menu> query = new LambdaQueryWrapper<>();
        if(StringUtils.isNotEmpty(dto.getName())){
            query.like(Menu::getName,dto.getName());
        }
        List<Menu> list = null;
        if (StringUtils.equalsIgnoreCase(tenantId, SystemConstant.ROOT_PARENT_ID)) {
            list = baseMapper.selectList(query);
        } else {
            query.eq(Menu::getTenantId, tenantId);
            list = baseMapper.selectList(query);
        }
        return list;
    }

    @Override
    public void delete(String[] ids) {
        List<String> idList = Arrays.asList(ids);
        idList.forEach(id -> {
            Long count = roleMenuMapper.selectCount(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, id));
            if (count > Constants.ZERO) {
                String mess = PropertyUtil.getProperty("MENU_ROLE_EXIST");
                throw new CmdException(100,mess);
            }
        });
        baseMapper.deleteBatchIds(idList);
    }

    @Override
    public void create(Menu entity) {
        saveOrUpdate(entity);
        LambdaQueryWrapper<MenuName> query = new LambdaQueryWrapper<>();
        query.eq(MenuName::getMenuId,entity.getId());
        menuNameMapper.delete(query);
        List<MenuName> names = entity.getNames();
        names.forEach(name->{
            name.setMenuId(entity.getId());
            menuNameMapper.insert(name);
        });
    }

    @Override
    public Menu get(String id) {
        Menu entity = baseMapper.selectById(id);
        if (ObjectUtils.isEmpty(entity)) {
            entity = new Menu();
        }
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getPid, PARENT);
        List<Menu> parents = baseMapper.selectList(queryWrapper);
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(Menu::getPid, PARENT);
        queryWrapper.eq(Menu::getType, MENU);
        List<Menu> childrens = baseMapper.selectList(queryWrapper);
        JSONArray metaParents = new JSONArray();
        parents.forEach(parent -> {
            JSONObject metaParent = new JSONObject();
            metaParent.put("id", parent.getId());
            metaParent.put("name", parent.getName());
            JSONArray metaChildrens = new JSONArray();
            childrens.forEach(children -> {
                if (StringUtils.equals(parent.getId(), children.getPid())) {
                    JSONObject metaChildren = new JSONObject();
                    metaChildren.put("id", children.getId());
                    metaChildren.put("name", children.getName());
                    metaChildrens.add(metaChildren);
                }
            });
            metaParent.put("childrens", metaChildrens);
            metaParents.add(metaParent);
        });
        entity.setResouces(metaParents);
        LambdaQueryWrapper<MenuName> queryName = new LambdaQueryWrapper<>();
        queryName.eq(MenuName::getMenuId,entity.getId());
        List<MenuName> names = menuNameMapper.selectList(queryName);
        entity.setNames(names);
        return entity;
    }

    @Override
    public List<String> listTreeByRoleId(String roleId) {
        LambdaQueryWrapper<Menu> query = new LambdaQueryWrapper<>();
        query.ne(Menu::getType, MENU);
        List<Menu> menus = baseMapper.selectList(query);
        List<String> menuIds = menus.stream().map(Menu::getId).collect(Collectors.toList());
        LambdaQueryWrapper<RoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleMenu::getRoleId, roleId);
        List<RoleMenu> list = roleMenuMapper.selectList(queryWrapper);
        List<String> checkedIds = list.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
        List<String> data = menuIds.stream().filter(item -> checkedIds.contains(item)).collect(Collectors.toList());
        return data;
    }

    @Override
    public void updateRoleMenuByRoleId(String roleId, List<String> menuIds) {
        LambdaQueryWrapper<RoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleMenu::getRoleId, roleId);
        roleMenuMapper.delete(queryWrapper);
        menuIds.forEach(id -> {
            RoleMenu entity = new RoleMenu(id, roleId);
            roleMenuMapper.insert(entity);
        });
    }
}
